﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;

namespace Common
{
   public class CookieHelper
    {
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="model"></param>
        public static void SaveUserData(ViewModel.LoginUser model)
        {
            //1.将用户信息对象转成json格式（序列化）
            //封装一个扩展方法，方便json格式序列化
            var userData = JsonConvert.SerializeObject(model);
            //2. 创建加密票据
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, "loginData", DateTime.Now, DateTime.Now.AddDays(1), false, userData);
            //3. 对票据进行加密
            string ticketEncrypt = FormsAuthentication.Encrypt(ticket);
            //4. 讲加密之后的用户信息写入到Cookie中
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketEncrypt);
            cookie.Path = FormsAuthentication.FormsCookiePath;

            // 5.将Cookie写入响应流中发送给客户端

            //获取http请求上下文
            HttpContext context = System.Web.HttpContext.Current;

            ////最好先将原来的移除掉
            context.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            context.Response.Cookies.Add(cookie);
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <returns></returns>
        public static ViewModel.LoginUser ReadUser()
        {
            HttpContext context = System.Web.HttpContext.Current;
            // 读取身份
            string ticketString = context.Request.Cookies[FormsAuthentication.FormsCookieName]?.Value;
            if (string.IsNullOrWhiteSpace(ticketString))
            {
                return default;
            }
            //解密
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(ticketString);
            string userData = ticket.UserData;
            // 反序列化用户资料
            ViewModel.LoginUser user = JsonConvert.DeserializeObject<ViewModel.LoginUser>(userData);
            return user;
        }
    }
}
